<template>
  <div class="v-upload">
    <img v-show="!mediaId" src="./add.png" @click="clickUpload" :style= "{'width': width, 'height': width}" alt="">
    <input ref="uploadinput" id="upload-file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="onChange"/>
    <img v-show="mediaId" ref="img" :style= "{'width': width, 'height': width}" :src="imagePath" alt="" @click="clickUpload">
  </div>
</template>
<script>
  import emitter from '@/vuego/mixins/emitter';
  import { fixImagePath } from '@/utils/tools';
  import { uploadImage } from '@/api/upload';

  export default {
    name: 'VUpload',
    props: {
      width: String,
      value: String,
    },
    mixins: [emitter],
    data(){
      return {
        mediaId: this.value
      }
    },
    watch: {
      value(val) {
        this.mediaId = val;
      },
    },
    computed: {
      imagePath() {
        return fixImagePath(this.mediaId);
      },
    },
    methods: {
      clickUpload(){
        // document.getElementById('upload-file').click();
        this.$refs.uploadinput.click();
      },
      onChange(e){
        let file = e.target.files[0];
        let formData = new FormData(); //创建form对象
        formData.append('file', file, file.name);//通过append向form对象添加数据
        uploadImage(formData).then((res)=>{
          const value = res.results.mediaId;
          this.mediaId = value;
          this.$emit('input', value);
          this.$emit('change', value);
          this.dispatch('VFormItem', 'v.form.change', [value]);
        }, (err) => {
          console.log(err);
        }, (process) => {
          console.log(process);
        })
      }
    },
    mounted(){
      console.log(this.value + "");
      this.$refs.img.onerror = () => {
        this.mediaId = '';
      }
    }
  };
</script>
